<template>
  <div class="comments-area">
    <div class="comments-title">
      发表评论<span v-if="total">（{{ total }}）</span>
    </div>
    <!-- 评论表单在顶部 -->
    <form class="comment-form" @submit.prevent="submitComment">
      <template v-if="!userInfoSaved">
        <div class="form-row">
          <div class="input-wrap">
            <input
              v-model="form.email"
              placeholder="邮箱（必填，推荐QQ邮箱-自动获取头像）"
              type="text"
              @blur="updateAvatar"
              :class="{ error: showError && emailError !== '' }"
            />
            <div v-if="showError && emailError" class="input-error">{{ emailError }}</div>
          </div>
          <div class="input-wrap">
            <input
              v-model="form.nickname"
              placeholder="昵称（必填）"
              :class="{ error: showError && !form.nickname }"
            />
            <div v-if="showError && !form.nickname" class="input-error">请输入昵称</div>
          </div>
        </div>
        <div class="form-row">
          <input v-model="form.homepage" placeholder="主页链接（可为空）" />
        </div>
      </template>
      <template v-else>
        <div class="user-info-bar">
          <img :src="form.avatar" :alt="form.nickname" class="avatar" />
          <span class="nickname">{{ form.nickname }}</span>
          <button type="button" class="reset-btn" @click="resetUserInfo">编辑信息</button>
        </div>
      </template>
      <div class="form-row">
        <div class="input-wrap">
          <textarea
            v-model="form.content"
            placeholder="一句走心评论，胜过千言万语"
            class="comment-content"
            :class="{ error: showError && !form.content }"
          ></textarea>
          <div v-if="showError && !form.content" class="input-error">请输入评论内容</div>
        </div>
      </div>
      <div class="form-actions">
        <button type="submit">发表评论</button>
      </div>
    </form>
    <!-- 评论列表 -->
    <div class="comments-list" v-if="pagedComments.length">
      <div v-for="comment in pagedComments" :key="comment.id" class="comment-item">
        <div class="main">
          <span class="avatar-wrap comment-avatar-wrap">
            <img :src="comment.avatar" :alt="comment.nickname" class="avatar" />
            <span v-if="comment.isAdmin" class="admin-badge" title="博主">
              <svg
                viewBox="0 0 16 16"
                width="14"
                height="14"
                style="display: block"
                fill="currentColor"
              >
                <path d="M7.5 1L2 9h4l-1.5 6L14 7h-4l1.5-6z" />
              </svg>
            </span>
          </span>
          <div class="content">
            <div class="info">
              <div class="user-info">
                <div class="user-basic-info">
                  <span class="nickname">{{ comment.nickname }}</span>
                  <span class="date">{{ formatDate(comment.createdAt) }}</span>
                </div>
                <!-- 设备信息标签和昵称时间在同一行 -->
                <div
                  class="device-info"
                  v-if="comment.ipRegion || comment.deviceType || comment.browser || comment.os"
                >
                  <span
                    v-if="comment.ipRegion"
                    class="location-tag"
                    :title="getLocationTitle(comment.ipRegion)"
                  >
                    <i class="ri-map-pin-line"></i>
                    {{ getLocationName(comment.ipRegion) }}
                  </span>
                  <span
                    v-if="comment.deviceType"
                    class="device-tag"
                    :title="getDeviceTitle(comment.deviceType)"
                  >
                    <i :class="getDeviceIcon(comment.deviceType)"></i>
                    {{ getDeviceName(comment.deviceType) }}
                  </span>
                  <span v-if="comment.browser" class="browser-tag" :title="comment.browser">
                    <i class="ri-global-line"></i>
                    {{ getBrowserName(comment.browser) }}
                  </span>
                  <span v-if="comment.os" class="os-tag" :title="comment.os">
                    <i class="ri-computer-line"></i>
                    {{ getOsName(comment.os) }}
                  </span>
                </div>
              </div>
            </div>
            <div class="text">{{ comment.content }}</div>
            <div class="actions">
              <button class="reply-btn" @click="toggleReplyForm(comment.id)">
                <i class="ri-reply-line"></i> 回复
              </button>
            </div>
          </div>
        </div>
        <!-- 精简版回复表单，仅允许同时展开一个 -->
        <form v-if="replyingToId === comment.id" class="reply-form" @submit.prevent="submitReply">
          <template v-if="!userInfoSaved">
            <div class="form-row">
              <div class="input-wrap">
                <input
                  v-model="replyForm.email"
                  placeholder="邮箱（必填）"
                  type="text"
                  :class="{ error: replyShowError && replyEmailError !== '' }"
                />
                <div v-if="replyShowError && replyEmailError" class="input-error">
                  {{ replyEmailError }}
                </div>
              </div>
              <div class="input-wrap">
                <input
                  v-model="replyForm.nickname"
                  placeholder="昵称（必填）"
                  :class="{ error: replyShowError && !replyForm.nickname }"
                />
                <div v-if="replyShowError && !replyForm.nickname" class="input-error">
                  请输入昵称
                </div>
              </div>
            </div>
            <div class="form-row">
              <input v-model="replyForm.homepage" placeholder="主页链接（可为空）" />
            </div>
          </template>
          <template v-else>
            <div class="user-info-bar">
              <img :src="form.avatar" :alt="form.nickname" class="avatar" />
              <span class="nickname">{{ form.nickname }}</span>
            </div>
          </template>
          <div class="form-row">
            <div class="input-wrap">
              <textarea
                v-model="replyForm.content"
                placeholder="回复内容（必填）"
                class="comment-content"
                :class="{ error: replyShowError && !replyForm.content }"
              ></textarea>
              <div v-if="replyShowError && !replyForm.content" class="input-error">
                请输入回复内容
              </div>
            </div>
          </div>
          <div class="form-actions">
            <button type="submit">发表回复</button>
            <button type="button" class="reset-btn" @click="cancelReply">取消</button>
          </div>
        </form>
        <!-- 多级回复展示区域 -->
        <div class="replies" v-if="comment.replies && comment.replies.length">
          <template v-for="reply in comment.replies" :key="reply.id">
            <!-- 回复项 -->
            <div class="reply-item" :class="{ 'nested-reply': reply.level > 2 }">
              <span class="avatar-wrap reply-avatar-wrap">
                <img :src="reply.avatar" :alt="reply.nickname" class="avatar" />
                <span v-if="reply.isAdmin" class="admin-badge" title="博主">
                  <svg
                    viewBox="0 0 16 16"
                    width="12"
                    height="12"
                    style="display: block"
                    fill="currentColor"
                  >
                    <path d="M7.5 1L2 9h4l-1.5 6L14 7h-4l1.5-6z" />
                  </svg>
                </span>
              </span>
              <div class="content">
                <div class="info">
                  <div class="user-info">
                    <div class="user-basic-info">
                      <span class="nickname">{{ reply.nickname }}</span>
                      <span v-if="reply.replyToUser" class="reply-to"
                        >@{{ reply.replyToUser }}</span
                      >
                      <span class="date">{{ formatDate(reply.createdAt) }}</span>
                    </div>
                    <!-- 设备信息标签和昵称时间在同一行 -->
                    <div
                      class="device-info"
                      v-if="reply.ipRegion || reply.deviceType || reply.browser || reply.os"
                    >
                      <span
                        v-if="reply.ipRegion"
                        class="location-tag"
                        :title="getLocationTitle(reply.ipRegion)"
                      >
                        <i class="ri-map-pin-line"></i>
                        {{ getLocationName(reply.ipRegion) }}
                      </span>
                      <span
                        v-if="reply.deviceType"
                        class="device-tag"
                        :title="getDeviceTitle(reply.deviceType)"
                      >
                        <i :class="getDeviceIcon(reply.deviceType)"></i>
                        {{ getDeviceName(reply.deviceType) }}
                      </span>
                      <span v-if="reply.browser" class="browser-tag" :title="reply.browser">
                        <i class="ri-global-line"></i>
                        {{ getBrowserName(reply.browser) }}
                      </span>
                      <span v-if="reply.os" class="os-tag" :title="reply.os">
                        <i class="ri-computer-line"></i>
                        {{ getOsName(reply.os) }}
                      </span>
                    </div>
                  </div>
                </div>
                <div class="text">{{ reply.content }}</div>
                <div class="actions">
                  <button class="reply-btn" @click="toggleReplyForm(reply.id)">
                    <i class="ri-reply-line"></i> 回复
                  </button>
                </div>
              </div>
            </div>

            <!-- 回复表单 -->
            <form v-if="replyingToId === reply.id" class="reply-form" @submit.prevent="submitReply">
              <template v-if="!userInfoSaved">
                <div class="form-row">
                  <div class="input-wrap">
                    <input
                      v-model="replyForm.email"
                      placeholder="邮箱（必填）"
                      type="text"
                      :class="{ error: replyShowError && replyEmailError !== '' }"
                    />
                    <div v-if="replyShowError && replyEmailError" class="input-error">
                      {{ replyEmailError }}
                    </div>
                  </div>
                  <div class="input-wrap">
                    <input
                      v-model="replyForm.nickname"
                      placeholder="昵称（必填）"
                      :class="{ error: replyShowError && !replyForm.nickname }"
                    />
                    <div v-if="replyShowError && !replyForm.nickname" class="input-error">
                      请输入昵称
                    </div>
                  </div>
                </div>
                <div class="form-row">
                  <input v-model="replyForm.homepage" placeholder="主页链接（可为空）" />
                </div>
              </template>
              <template v-else>
                <div class="user-info-bar">
                  <img :src="form.avatar" :alt="form.nickname" class="avatar" />
                  <span class="nickname">{{ form.nickname }}</span>
                </div>
              </template>
              <div class="form-row">
                <div class="input-wrap">
                  <textarea
                    v-model="replyForm.content"
                    placeholder="回复内容（必填）"
                    class="comment-content"
                    :class="{ error: replyShowError && !replyForm.content }"
                  ></textarea>
                  <div v-if="replyShowError && !replyForm.content" class="input-error">
                    请输入回复内容
                  </div>
                </div>
              </div>
              <div class="form-actions">
                <button type="submit">发表回复</button>
                <button type="button" class="reset-btn" @click="cancelReply">取消</button>
              </div>
            </form>
          </template>
        </div>
      </div>
      <!-- 分页 -->
      <div class="pagination-bar" v-if="total > pageSize">
        <button :disabled="currentPage === 1" @click="changePage(currentPage - 1)">上一页</button>
        <span>第 {{ currentPage }} / {{ totalPages }} 页</span>
        <button :disabled="currentPage === totalPages" @click="changePage(currentPage + 1)">
          下一页
        </button>
      </div>
    </div>
    <div v-else class="no-comments"><i class="ri-chat-off-line"></i> 暂无评论，快来抢沙发吧！</div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { addArticleComment } from '@/api/article'
import { ElMessage } from 'element-plus'

const props = defineProps({
  comments: Array,
  articleId: { type: [String, Number], required: false },
  pagination: { type: Object, default: () => ({ total: 0, current: 1, pages: 1, size: 10 }) },
})
const emit = defineEmits(['submit', 'page-change'])
const defaultAvatar = 'https://secure.gravatar.com/avatar/?s=80&d=mp'

// 表单数据
const form = ref({
  email: '',
  nickname: '',
  homepage: '',
  content: '',
  avatar: defaultAvatar,
})

// 本地存储键
const STORAGE_KEY = 'blog_comment_userinfo'

// 是否已保存用户信息
const userInfoSaved = ref(false)

// 校验控制
const showError = ref(false)

// 邮箱格式校验
const emailError = ref('')

// 回复表单相关
const replyingToId = ref(null)
const replyForm = ref({
  email: '',
  nickname: '',
  homepage: '',
  content: '',
  parentId: null, // 添加父评论ID字段
})
const replyShowError = ref(false)
const replyEmailError = ref('')

// 分页相关 - 使用从父组件传递的分页信息
const total = computed(() => props.pagination.total || 0)
const currentPage = computed(() => props.pagination.current || 1)
const pageSize = computed(() => props.pagination.size || 10)
const totalPages = computed(() => props.pagination.pages || 1)

// 直接使用 comments，不需要客户端分页
const pagedComments = computed(() => props.comments || [])

// 读取本地用户信息
function loadUserInfo() {
  const saved = localStorage.getItem(STORAGE_KEY)
  if (saved) {
    try {
      const info = JSON.parse(saved)
      form.value.email = info.email || ''
      form.value.nickname = info.nickname || ''
      form.value.homepage = info.homepage || ''
      form.value.avatar = info.avatar || defaultAvatar
      userInfoSaved.value = !!(info.email && info.nickname)
    } catch {
      // 解析失败时忽略，保持默认值
    }
  }
}

// 保存用户信息到本地
function saveUserInfo() {
  const info = {
    email: form.value.email,
    nickname: form.value.nickname,
    homepage: form.value.homepage,
    avatar: form.value.avatar,
  }
  localStorage.setItem(STORAGE_KEY, JSON.stringify(info))
  userInfoSaved.value = true
}

// 重置用户信息，允许重新输入
function resetUserInfo() {
  userInfoSaved.value = false
  form.value.email = ''
  form.value.nickname = ''
  form.value.homepage = ''
  form.value.avatar = defaultAvatar
  localStorage.removeItem(STORAGE_KEY)
}

// QQ邮箱自动获取QQ头像
function updateAvatar() {
  const email = form.value.email.trim()
  const qqMatch = email.match(/^([1-9][0-9]{4,10})@qq\.com$/i)
  if (qqMatch) {
    form.value.avatar = `https://q2.qlogo.cn/headimg_dl?dst_uin=${qqMatch[1]}&spec=100`
  } else {
    form.value.avatar = defaultAvatar
  }
}

// 邮箱格式校验
function validateEmail(email) {
  if (!email) return '请输入邮箱'
  // 简单邮箱正则
  const re = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
  if (!re.test(email)) return '邮箱格式不正确'
  return ''
}

// 提交评论
async function submitComment() {
  showError.value = false
  emailError.value = validateEmail(form.value.email)
  if (emailError.value || !form.value.nickname || !form.value.content) {
    showError.value = true
    return
  }
  // 首次填写信息时保存
  if (!userInfoSaved.value) {
    saveUserInfo()
  }
  try {
    await addArticleComment({
      targetId: String(props.articleId || ''),
      email: form.value.email,
      nickname: form.value.nickname,
      content: form.value.content,
      parentId: '-1',
      targetType: '1',
    })
    emit('submit', { ...form.value })
    ElMessage.success('操作成功！')
    form.value.content = ''
  } catch (e) {
    // 失败提示可在这里接入全局消息
    console.log(e)
  }
}

// 日期格式化
function formatDate(dateString) {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' })
}

// 设备信息处理函数
function getDeviceIcon(deviceType) {
  const iconMap = {
    pc: 'ri-computer-line',
    mobile: 'ri-smartphone-line',
    tablet: 'ri-tablet-line',
    android: 'ri-android-line',
    ios: 'ri-apple-line',
  }
  return iconMap[deviceType] || 'ri-device-line'
}

function getDeviceName(deviceType) {
  const nameMap = {
    pc: 'PC',
    mobile: '手机',
    tablet: '平板',
    android: '安卓',
    ios: 'iOS',
  }
  return nameMap[deviceType] || deviceType
}

function getDeviceTitle(deviceType) {
  return `设备类型: ${getDeviceName(deviceType)}`
}

function getBrowserName(browser) {
  // 提取浏览器名称，去掉版本号
  if (browser.includes('Chrome')) return 'Chrome'
  if (browser.includes('Firefox')) return 'Firefox'
  if (browser.includes('Safari')) return 'Safari'
  if (browser.includes('Edge')) return 'Edge'
  if (browser.includes('Opera')) return 'Opera'
  return browser.split(' ')[0] || browser
}

function getOsName(os) {
  // 简化操作系统名称
  if (os.includes('Windows')) return 'Windows'
  if (os.includes('macOS')) return 'macOS'
  if (os.includes('Linux')) return 'Linux'
  if (os.includes('Android')) return 'Android'
  if (os.includes('iOS')) return 'iOS'
  return os
}

// 区域信息处理函数
function getLocationName(ipRegion) {
  if (!ipRegion) return ''

  // 解析区域信息，格式通常是 "0|0|0|内网IP|内网IP" 或 "国家|省份|城市|运营商|详细地址"
  const parts = ipRegion.split('|')

  if (parts.length >= 5) {
    const country = parts[0]
    const province = parts[1]
    const city = parts[2]
    const detail = parts[4]

    // 如果是内网IP，显示为"内网"
    if (detail === '内网IP' || detail === '内网') {
      return '内网'
    }

    // 优先显示城市，如果没有城市则显示省份
    if (city && city !== '0' && city !== '') {
      return city
    } else if (province && province !== '0' && province !== '') {
      return province
    } else if (country && country !== '0' && country !== '') {
      return country
    }
  }

  // 如果解析失败，返回原始信息
  return ipRegion
}

function getLocationTitle(ipRegion) {
  if (!ipRegion) return ''

  const parts = ipRegion.split('|')
  if (parts.length >= 5) {
    const country = parts[0]
    const province = parts[1]
    const city = parts[2]
    const isp = parts[3]

    let location = ''
    if (country && country !== '0') location += country
    if (province && province !== '0' && province !== country)
      location += (location ? ' ' : '') + province
    if (city && city !== '0' && city !== province) location += (location ? ' ' : '') + city
    if (isp && isp !== '0') location += (location ? ' · ' : '') + isp

    return location || ipRegion
  }

  return ipRegion
}

/**
 * 切换回复表单显示状态
 * @param {string|number} id - 要回复的评论ID
 */
function toggleReplyForm(id) {
  if (replyingToId.value === id) {
    replyingToId.value = null
  } else {
    replyingToId.value = id
    // parentId 应该始终是被回复评论的ID，而不是一级评论的ID
    replyForm.value.parentId = id
    // 自动填充本地信息
    if (userInfoSaved.value) {
      replyForm.value.email = form.value.email
      replyForm.value.nickname = form.value.nickname
      replyForm.value.homepage = form.value.homepage
    } else {
      replyForm.value.email = ''
      replyForm.value.nickname = ''
      replyForm.value.homepage = ''
    }
    replyForm.value.content = ''
    replyShowError.value = false
    replyEmailError.value = ''
  }
}
function cancelReply() {
  replyingToId.value = null
}
function validateReplyEmail(email) {
  if (!email) return '请输入邮箱'
  const re = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
  if (!re.test(email)) return '邮箱格式不正确'
  return ''
}
/**
 * 提交回复
 */
async function submitReply() {
  replyShowError.value = false
  replyEmailError.value = validateReplyEmail(replyForm.value.email)
  if (replyEmailError.value || !replyForm.value.nickname || !replyForm.value.content) {
    replyShowError.value = true
    return
  }

  try {
    await addArticleComment({
      targetId: String(props.articleId || ''),
      email: replyForm.value.email,
      nickname: replyForm.value.nickname,
      content: replyForm.value.content,
      parentId: String(replyForm.value.parentId || ''),
      targetType: '1',
    })

    // 提交成功后触发父组件重新加载评论
    emit('submit', { ...replyForm.value })
    ElMessage.success('回复成功！')

    // 重置表单
    replyingToId.value = null
    replyForm.value.content = ''
    replyForm.value.homepage = ''
    replyForm.value.parentId = null
  } catch (error) {
    console.error('回复失败:', error)
    ElMessage.error('回复失败，请重试')
  }
}

function changePage(page) {
  emit('page-change', page)
  replyingToId.value = null // 翻页时关闭回复表单
}

// 页面加载时自动填充
onMounted(loadUserInfo)
</script>

<style lang="scss" scoped>
.comments-area {
  margin-top: 32px;
  background: #fff;
  border-radius: 14px;
  box-shadow: 0 2px 16px rgba(81, 138, 255, 0.06);
  padding: 32px 24px 24px 24px;
  @media (max-width: 600px) {
    padding: 16px 10px 12px 10px;
    border-radius: 8px;
  }
  .comments-title {
    font-size: 18px;
    font-weight: 700;
    color: #23272f;
    margin-bottom: 18px;
    letter-spacing: 1px;
    @media (max-width: 600px) {
      font-size: 15px;
      margin-bottom: 10px;
    }
  }
  .comment-form {
    margin-bottom: 28px;
    display: flex;
    flex-direction: column;
    gap: 0;
    .form-row {
      display: flex;
      gap: 14px;
      margin-bottom: 12px;
      @media (max-width: 600px) {
        flex-direction: column;
        gap: 6px;
        margin-bottom: 8px;
      }
      .input-wrap {
        flex: 1;
        display: flex;
        flex-direction: column;
        position: relative;
      }
      input,
      textarea {
        flex: 1;
        border: 1px solid #e3e8ee;
        border-radius: 7px;
        padding: 10px 12px;
        font-size: 15px;
        background: #f7faff;
        color: #23272f;
        transition: border 0.18s;
        outline: none;
        &:focus {
          border-color: #518aff;
        }
        &.error {
          border-color: #ffb300;
        }
      }
      textarea {
        min-height: 100px;
        resize: vertical;
        &.comment-content {
          min-height: 100px;
        }
      }
      .input-error {
        color: #ffb300;
        font-size: 12px;
        margin-top: 3px;
        margin-left: 2px;
        line-height: 1.4;
      }
      /* 去除原生校验气泡 */
      input:invalid,
      textarea:invalid {
        box-shadow: none;
      }
    }
    .user-info-bar {
      display: flex;
      align-items: center;
      gap: 12px;
      margin-bottom: 10px;
      .avatar {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        object-fit: cover;
        background: #f7faff;
        border: 1.5px solid #e3e8ee;
      }
      .nickname {
        font-weight: 600;
        color: #23272f;
        font-size: 15px;
      }
      .reset-btn {
        background: none;
        border: none;
        color: #518aff;
        font-size: 13px;
        cursor: pointer;
        border-radius: 5px;
        padding: 2px 10px;
        transition: background 0.18s;
        &:hover {
          background: #f7faff;
        }
      }
    }
    .form-actions {
      display: flex;
      justify-content: flex-end;
      margin-top: 2px;
      button[type='submit'] {
        background: linear-gradient(90deg, #518aff 60%, #7daaff 100%);
        color: #fff;
        border: none;
        border-radius: 7px;
        padding: 7px 28px;
        font-size: 15px;
        font-weight: 600;
        cursor: pointer;
        box-shadow: 0 1px 4px rgba(81, 138, 255, 0.07);
        transition: background 0.18s;
        &:hover {
          background: #4070d4;
        }
      }
    }
  }
  .comments-list {
    .comment-item {
      margin-bottom: 24px;
      padding-bottom: 18px;
      border-bottom: 1px solid #f0f4fa;
      &:last-child {
        border-bottom: none;
      }
      .main {
        display: flex;
        gap: 14px;
        .avatar-wrap {
          position: relative;
          display: flex;
          flex-shrink: 0;
        }
        .comment-avatar-wrap,
        .reply-avatar-wrap {
          width: 40px;
          height: 40px;
        }
        .avatar {
          width: 100%;
          height: 100%;
          display: block;
          border-radius: 50%;
          object-fit: cover;
          background: #f7faff;
          border: 1.5px solid #e3e8ee;
        }
        .content {
          flex: 1;
          .info {
            display: flex;
            flex-direction: column;
            gap: 4px;
            .user-info {
              display: flex;
              align-items: center;
              gap: 10px;
              flex-wrap: wrap;
              .nickname {
                font-weight: 600;
                color: #23272f;
                font-size: 15px;
              }
              .date {
                font-size: 13px;
                color: #7a8599;
              }
              .device-info {
                display: flex;
                align-items: center;
                gap: 6px;
                flex-wrap: wrap;
                .location-tag,
                .device-tag,
                .browser-tag,
                .os-tag {
                  display: inline-flex;
                  align-items: center;
                  gap: 3px;
                  background: #f8fafc;
                  color: #64748b;
                  font-size: 10px;
                  padding: 1px 5px;
                  border-radius: 6px;
                  border: 1px solid #e2e8f0;
                  transition: all 0.2s ease;
                  cursor: help;
                  i {
                    font-size: 10px;
                  }
                  &:hover {
                    background: #f1f5f9;
                    color: #475569;
                    border-color: #cbd5e1;
                  }
                }
                .location-tag {
                  background: #f0f8ff;
                  color: #518aff;
                  border-color: #c7d2fe;
                  &:hover {
                    background: #e0e7ff;
                    color: #3b82f6;
                    border-color: #3b82f6;
                  }
                }
              }
            }
          }
          .text {
            margin: 7px 0 0 0;
            font-size: 15px;
            color: #23272f;
            line-height: 1.7;
          }
          .actions {
            margin-top: 10px;
            display: flex;
            align-items: center;
            justify-content: flex-start;
          }
        }
      }
      .replies {
        margin-left: 54px;
        margin-top: 8px;
        .reply-item {
          display: flex;
          gap: 8px;
          margin-bottom: 6px;
          position: relative;

          // 多级评论的视觉层级
          &.nested-reply {
            margin-left: 20px; // 三级及以上评论向右缩进
            position: relative;

            // 添加连接线
            &::before {
              content: '';
              position: absolute;
              left: -16px;
              top: 0;
              bottom: 0;
              width: 1px;
              background: #e3e8ee;
            }

            &::after {
              content: '';
              position: absolute;
              left: -16px;
              top: 14px;
              width: 12px;
              height: 1px;
              background: #e3e8ee;
            }
          }

          .avatar-wrap {
            position: relative;
            display: flex;
            flex-shrink: 0;
          }
          .reply-avatar-wrap {
            width: 28px;
            height: 28px;
          }
          .avatar {
            width: 100%;
            height: 100%;
            display: block;
            border-radius: 50%;
            object-fit: cover;
            background: #f7faff;
            border: 1.5px solid #e3e8ee;
          }
          .content {
            .info {
              display: flex;
              flex-direction: column;
              gap: 4px;
              .user-info {
                display: flex;
                align-items: center;
                gap: 8px;
                flex-wrap: wrap;
                .nickname {
                  color: #23272f;
                  font-size: 14px;
                  font-weight: 500;
                }
                .reply-to {
                  color: #518aff;
                  font-size: 12px;
                  background: #f0f4fa;
                  padding: 2px 6px;
                  border-radius: 4px;
                  font-weight: 500;
                  margin-right: 4px;
                }
                .date {
                  font-size: 12px;
                  color: #7a8599;
                  margin-left: auto; // 让时间右对齐
                }
                .device-info {
                  display: flex;
                  align-items: center;
                  gap: 4px;
                  flex-wrap: wrap;
                  .location-tag,
                  .device-tag,
                  .browser-tag,
                  .os-tag {
                    display: inline-flex;
                    align-items: center;
                    gap: 2px;
                    background: #f8fafc;
                    color: #64748b;
                    font-size: 9px;
                    padding: 1px 4px;
                    border-radius: 4px;
                    border: 1px solid #e2e8f0;
                    transition: all 0.2s ease;
                    cursor: help;
                    i {
                      font-size: 9px;
                    }
                    &:hover {
                      background: #f1f5f9;
                      color: #475569;
                      border-color: #cbd5e1;
                    }
                  }
                  .location-tag {
                    background: #f0f8ff;
                    color: #518aff;
                    border-color: #c7d2fe;
                    &:hover {
                      background: #e0e7ff;
                      color: #3b82f6;
                      border-color: #3b82f6;
                    }
                  }
                }
              }
            }
            .text {
              font-size: 14px;
              color: #23272f;
              line-height: 1.6;
              margin-top: 4px;
            }
            .actions {
              margin-top: 8px;
              display: flex;
              align-items: center;
              justify-content: flex-start;
            }
          }
        }
        .reply-form {
          margin-left: -54px;
          width: calc(100% + 54px);
          box-sizing: border-box;
        }
      }
    }
  }
  .no-comments {
    color: #7a8599;
    font-size: 15px;
    text-align: center;
    margin: 32px 0;
    i {
      font-size: 22px;
      margin-right: 6px;
    }
  }
}
.reply-form {
  margin: 16px 0 8px 0;
  background: #f7faff;
  border-radius: 8px;
  padding: 16px 16px 12px 16px;
  box-shadow: 0 1px 6px rgba(81, 138, 255, 0.06);
  display: flex;
  flex-direction: column;
  gap: 0;
  width: 100%;
  box-sizing: border-box;
  .user-info-bar {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 8px;
    .avatar {
      width: 28px;
      height: 28px;
      border-radius: 50%;
      object-fit: cover;
      background: #f7faff;
      border: 1.5px solid #e3e8ee;
    }
    .nickname {
      font-weight: 600;
      color: #23272f;
      font-size: 14px;
    }
  }
  @media (max-width: 600px) {
    margin-left: 0 !important;
    width: 100% !important;
  }
  .form-row {
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin-bottom: 10px;
  }
  .input-wrap {
    display: flex;
    flex-direction: column;
    position: relative;
  }
  input,
  textarea {
    border: 1px solid #e3e8ee;
    border-radius: 7px;
    padding: 8px 10px;
    font-size: 14px;
    background: #f7faff;
    color: #23272f;
    transition: border 0.18s;
    outline: none;
    &:focus {
      border-color: #518aff;
    }
    &.error {
      border-color: #ffb300;
    }
  }
  textarea {
    min-height: 60px;
    resize: vertical;
  }
  .input-error {
    color: #ffb300;
    font-size: 12px;
    margin-top: 3px;
    margin-left: 2px;
    line-height: 1.4;
  }
  .form-actions {
    display: flex;
    gap: 10px;
    margin-top: 2px;
    button[type='submit'] {
      background: linear-gradient(90deg, #518aff 60%, #7daaff 100%);
      color: #fff;
      border: none;
      border-radius: 7px;
      padding: 5px 18px;
      font-size: 14px;
      font-weight: 600;
      cursor: pointer;
      box-shadow: 0 1px 4px rgba(81, 138, 255, 0.07);
      transition: background 0.18s;
      &:hover {
        background: #4070d4;
      }
    }
    .reset-btn {
      background: none;
      border: none;
      color: #518aff;
      font-size: 13px;
      cursor: pointer;
      border-radius: 5px;
      padding: 2px 10px;
      transition: background 0.18s;
      &:hover {
        background: #e3e8ee;
      }
    }
  }
}
.comments-area .replies .reply-form {
  @media (max-width: 600px) {
    margin-left: 0 !important;
    width: 100% !important;
  }
}
.pagination-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 18px;
  margin: 18px 0 0 0;
  button {
    background: #f7faff;
    border: none;
    border-radius: 6px;
    color: #518aff;
    font-size: 14px;
    padding: 5px 16px;
    cursor: pointer;
    transition: background 0.18s;
    &:disabled {
      color: #bfc8da;
      cursor: not-allowed;
      background: #f0f4fa;
    }
    &:hover:not(:disabled) {
      background: #e3e8ee;
    }
  }
  span {
    color: #7a8599;
    font-size: 14px;
  }
}
.reply-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  background: #f4f6fa;
  border: none;
  color: #518aff;
  font-size: 13px;
  font-weight: 500;
  border-radius: 16px;
  padding: 3px 14px 3px 10px;
  cursor: pointer;
  transition:
    background 0.18s,
    color 0.18s;
  i {
    font-size: 15px;
    margin-right: 2px;
  }
  &:hover {
    background: #e3e8ee;
    color: #4070d4;
  }
}
.admin-badge {
  position: absolute;
  right: 0;
  bottom: 0;
  background: #ffb300;
  color: #fff;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  box-shadow: 0 1px 4px rgba(81, 138, 255, 0.1);
  z-index: 2;
  cursor: pointer;
}
.comment-avatar-wrap .admin-badge {
  width: 18px;
  height: 18px;
}
.reply-avatar-wrap .admin-badge {
  width: 14px;
  height: 14px;
}
@media (max-width: 600px) {
  .comments-area {
    padding: 16px 10px 12px 10px;
    .comment-form {
      margin-bottom: 18px;
      .form-row input,
      .form-row textarea {
        font-size: 13px;
        padding: 7px 8px;
      }
      .form-actions button[type='submit'] {
        font-size: 13px;
        padding: 5px 16px;
      }
      .user-info-bar .avatar {
        width: 26px;
        height: 26px;
      }
      .user-info-bar .nickname {
        font-size: 13px;
      }
    }
    .comments-list .comment-item .main .avatar {
      width: 32px;
      height: 32px;
    }
    .comments-list .comment-item .main .content .info {
      .user-info {
        flex-direction: column;
        align-items: flex-start;
        gap: 4px;
        // 移动端时，昵称和时间在同一行
        .user-basic-info {
          display: flex;
          align-items: center;
          gap: 8px;
          flex-wrap: wrap;
        }
        .nickname {
          font-size: 13px;
        }
        .device-info {
          display: flex;
          align-items: center;
          gap: 4px;
          flex-wrap: wrap;
          .location-tag,
          .device-tag,
          .browser-tag,
          .os-tag {
            font-size: 8px;
            padding: 1px 3px;
            i {
              font-size: 8px;
            }
          }
        }
      }
    }
    .comments-list .comment-item .main .content .text {
      font-size: 13px;
    }
    .comments-list .comment-item .replies {
      margin-left: 32px;

      .reply-item {
        &.nested-reply {
          margin-left: 16px; // 移动端减少缩进

          &::before {
            left: -12px;
          }

          &::after {
            left: -12px;
            width: 8px;
          }
        }

        .avatar {
          width: 22px;
          height: 22px;
        }
        .content .info .nickname {
          font-size: 12px;
        }
        .content .text {
          font-size: 12px;
        }
        .content .info {
          .user-info {
            flex-direction: column;
            align-items: flex-start;
            gap: 4px;
            // 移动端时，昵称、@回复、时间在同一行
            .user-basic-info {
              display: flex;
              align-items: center;
              gap: 6px;
              flex-wrap: wrap;
            }
            .reply-to {
              font-size: 11px;
              padding: 1px 4px;
              margin-right: 2px;
            }
            .date {
              margin-left: 0;
            }
            .device-info {
              display: flex;
              align-items: center;
              gap: 3px;
              flex-wrap: wrap;
              .location-tag,
              .device-tag,
              .browser-tag,
              .os-tag {
                font-size: 7px;
                padding: 1px 2px;
                i {
                  font-size: 7px;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
